<template>
  <div>
    <li>
      <label>
        <input type="checkbox" :checked="todoObj.done" @change="handleCheck(todoObj.id)"/>
        <span v-show="!todoObj.isEdit">{{todoObj.title}}</span>
        <input type="text" 
        :value="todoObj.title" 
        v-show="todoObj.isEdit"
        ref = "editInput" 
        @blur="handleBlur(todoObj,$event)"
        >
      </label>
      <button  class="btn btn-danger" @click="handleDelete(todoObj.id)">删除</button>
      <button class="btn btn-edit" 
      v-show="!todoObj.isEdit" 
      @click="handleEdit(todoObj)" >编辑</button>
    </li>
  </div>
</template>

<script>
export default {
  name:'TodoItem',
  props:['todoObj'],
  methods:{
    handleCheck(id){
      //通知App组件将对应id的Todo对象done取反
      this.$bus.$emit('checkTodo',id)
    },
    handleDelete(id){
      //通知App组件删除todo
      this.$bus.$emit('deleteTodo',id)
    },
    handleEdit(todo){
      if(todo.isEdit != undefined){
        console.log('已经存在isEdit')
        todo.isEdit = true
      }else{
        this.$set(todo,'isEdit',true)
      }
      // 直接获取焦点无法生效，因为input还没挂载到页面
      // this.$refs.editInput.focus()
      
      // 使用nextTick，在下一次DOM更新结束后执行指定的回调
      // 什么时候使用？：在要基于更新后的新DOM进行某些操作时使用
      this.$nextTick(()=>{
        this.$refs.editInput.focus()
      })
    },
    handleBlur(todo,e){
      todo.isEdit = false
      if(!e.target.value.trim()) return alert('输入不能为空！')
      this.$bus.$emit('updateTodo',todo.id,e.target.value)
    }
  }
}
</script>

<style scoped>
  /*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #ddd;
}

li:hover button {
  display: block;
}
</style>